<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人信息</h2>
      <p>管理您的账户信息和设置</p>
    </div>

    <div class="profile-content">
      <el-form label-position="top" label-width="120" class="custom-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="头像" class="avatar-form-item">
              <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="customUpload"
              >
                <div class="avatar-wrapper">
                  <img
                      :src="saveUserForm.avatar || defaultAvatar"
                      class="avatar-image"
                      @load="handleImageLoad"
                  />
                  <div class="upload-mask">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <span class="upload-text">更换头像</span>
                  </div>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="账号状态">
              <el-radio-group v-model="saveUserForm.status" class="radio-group" disabled>
                <el-radio border label="正常" :value=1></el-radio>
                <el-radio border label="禁用" :value=0></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" class="edit-button-col">
            <el-button type="primary" @click="dialogVisible=true" class="edit-profile-btn">
              <el-icon><Edit /></el-icon> 修改个人信息
            </el-button>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="info-row">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input
                  placeholder="请输入用户名"
                  v-model="saveUserForm.username"
                  disabled
                  class="form-input"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input
                  placeholder="请输入手机号"
                  v-model="saveUserForm.phone"
                  disabled
                  class="form-input"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="info-row">
          <el-col :span="12">
            <el-form-item label="密码">
              <el-input
                  placeholder="请输入密码"
                  v-model="saveUserForm.password"
                  disabled
                  class="form-input"
                  type="password"
                  show-password
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货地址">
              <el-input
                  placeholder="请输入收货地址"
                  v-model="saveUserForm.address"
                  disabled
                  class="form-input"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog
        title="个人信息修改"
        v-model="dialogVisible"
        :before-close="handleClose"
        width="60%"
        class="profile-dialog"
    >
      <div class="dialog-content">
        <el-form label-position="top" label-width="120" class="custom-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="头像" class="avatar-form-item">
                <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="customUpload"
                >
                  <div class="avatar-wrapper">
                    <img
                        :src="saveUserForm.avatar || defaultAvatar"
                        class="avatar-image"
                    />
                    <div class="upload-mask">
                      <el-icon class="upload-icon"><Plus /></el-icon>
                      <span class="upload-text">更换头像</span>
                    </div>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号状态">
                <el-radio-group v-model="saveUserForm.status" class="radio-group" disabled>
                  <el-radio border label="正常" :value=1></el-radio>
                  <el-radio border label="禁用" :value=0></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <el-form-item label="用户名">
                <el-input
                    placeholder="请输入用户名"
                    v-model="saveUserForm.username"
                    :disabled="saveUserForm.id!=null"
                    class="form-input"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号">
                <el-input
                    placeholder="请输入手机号"
                    v-model="saveUserForm.phone"
                    class="form-input"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <el-form-item label="密码">
                <el-input
                    placeholder="请输入新密码"
                    v-model="saveUserForm.password"
                    class="form-input"
                    type="password"
                    show-password
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货地址">
                <el-input
                    placeholder="请输入收货地址"
                    v-model="saveUserForm.address"
                    class="form-input"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="handleClose" class="dialog-cancel-btn">取消</el-button>
        <el-button type="primary" @click="saveUser" class="dialog-save-btn">
          <el-icon><Check /></el-icon> 保存修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Check } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const saveUserForm = ref({
  id: null,
  username: '',
  password: '',
  phone: '',
  status: 1,
  address: '',
  avatar: ''
})

const dialogVisible = ref(false)

const handleImageLoad = (e) => {
  console.log('头像图片加载完成', e.target)
}

const loadPersonal = async () => {
  try {
    const response = await axios.get(BASE_URL+'/api/v1/users/select')
    if (response.data.code === 2000) {
      saveUserForm.value = response.data.data
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('获取个人信息失败')
  }
}

const saveUser = async () => {
  try {
    const response = await axios.post(BASE_URL+'/api/v1/users/private/revise', saveUserForm.value)
    if (response.data.code === 2000) {
      ElMessage.success('修改成功！')
      loadPersonal()
      dialogVisible.value = false
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const handleClose = () => {
  if (confirm('确认取消保存用户吗？')) {
    loadPersonal()
    dialogVisible.value = false
  }
}

//  自定义上传
const customUpload = async (options) => {
  const { file } = options
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', saveUserForm.value.id || '123')

    const response = await axios.post(BASE_URL+'/v1/file/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    if (response.data.code === 2000) {
      ElMessage.success('头像上传成功')
      saveUserForm.value.avatar = response.data.data
    } else {
      throw new Error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传出错：' + error.message)
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  return isImage && isLt5M
}

onMounted(() => {
  loadPersonal()
})
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f7f9fc;
  min-height: 100vh;
}

.profile-header {
  margin-bottom: 30px;
  padding: 15px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.profile-header h2 {
  margin: 0;
  font-size: 22px;
  color: #333;
  font-weight: 600;
}

.profile-header p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #666;
}

.profile-content {
  background-color: #fff;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.custom-form {
  margin-top: 20px;
}

.form-input {
  width: 100%;
}

.radio-group {
  display: flex;
  gap: 10px;
}

.info-row {
  margin-bottom: 20px;
}

.avatar-form-item {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.avatar-uploader {
  border: 1px dashed #dcdfe6;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  background-color: #f5f7fa;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  min-width: 100%;
  min-height: 100%;
  vertical-align: bottom;
  transition: transform 0.3s;
}

.avatar-uploader:hover .avatar-image {
  transform: scale(1.05);
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  border-radius: 50%;
}

.avatar-uploader:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.upload-text {
  font-size: 12px;
  font-weight: 500;
}

.edit-button-col {
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
}

.edit-profile-btn {
  padding: 10px 20px;
  height: auto;
}

.profile-dialog {
  border-radius: 8px;
}

.profile-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

.profile-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.dialog-cancel-btn {
  padding: 10px 20px;
  height: auto;
}

.dialog-save-btn {
  padding: 10px 20px;
  height: auto;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }

  .profile-header {
    margin-bottom: 20px;
    padding: 10px;
  }

  .profile-content {
    padding: 15px;
  }

  .avatar-uploader {
    width: 100px;
    height: 100px;
  }

  .edit-button-col {
    justify-content: flex-start;
    margin-top: 15px;
  }
}
</style>